using System;
using System.Timers;
using HashFoo.Core;
using HashFoo.Rest.Common;

namespace HashFoo.Rest.CommonTests.MockResources
{
    public class WebClientOperationMock : IWebClientOperation
    {
        public event EventHandler OnCanceled;

        Timer _timer;
        readonly object _syncLock = new object();

        public WebClientOperationMock(Timer timer)
        {
            _timer = timer;
        }

        public void MarkAsComplete(Action callback = null)
        {
            lock (_syncLock)
            {
                if (_timer == null) return;

                _timer.Stop();
                _timer.Dispose();
                _timer = null;

                if (callback != null) callback();
                OnCompleted();
            }
        }

        public void Cancel()
        {
            if (OnCanceled != null) OnCanceled(this, EventArgs.Empty);
            OnCompleted();
        }

        /// <summary>
        /// True if the operation is no longer active.  If true, it does not necessarily mean
        ///             the operation was completed successfully, just that its done.
        /// </summary>
        public bool IsDone { get; set; }

        public event Action Completed;

        public void OnCompleted()
        {
            var handler = Completed;
            if (handler != null) handler();
        }
    }
}